package com.ericsson.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ericsson.web.core.Constants;
import com.ericsson.web.core.HSQLDatabase;
import com.ericsson.web.core.IDatabase;
import com.ericsson.web.core.Utils;

public class RegisterUser extends HttpServlet {

	private final static String USER_NAME="username";
	private final static String PASSWORD="password";
	private final static String DESCRIPTION="description";
	
	@Override
	protected void doPost(HttpServletRequest request, 
			HttpServletResponse response) 
	throws ServletException, IOException {
		doGet(request, response);
	}
	
	@Override
	protected void doGet(HttpServletRequest request, 
			HttpServletResponse response) 
	throws ServletException, IOException {
		String  username = request.getParameter(USER_NAME);
		String  password = request.getParameter(PASSWORD);
		if(Utils.isEmpty(username) || Utils.isEmpty(password))  {
			response.sendRedirect(Constants.REGISTER_PAGE);
			return;
		}
		String description = request.getParameter(DESCRIPTION);
		if(description == null) {
			description = "";
		}
		IDatabase db = HSQLDatabase.getInstance();
		int userId = db.registerUser(username, password, description);
		if(userId >= 0) {
			request.getSession().setAttribute(Constants.USERID, userId);
			response.sendRedirect(Constants.INDEX_PAGE);
			return;
		}
		response.sendRedirect(Constants.REGISTER_PAGE);
		return;
	}
}
